package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.AddressDeleteFailException;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public void add(Address address) {
        addressDao.add(address);
        //将点击确定后的图片保存在另一个redis数据库中
        Jedis resource = jedisPool.getResource();
        String image = address.getImage();
        if (image != null) {
            resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, image);
            resource.close();
        }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Address> page = addressDao.findPage(queryString);
        long total = page.getTotal();
        return new PageResult(total, page);
    }

    @Override
    public void edit(Address address) {
        addressDao.edit(address);
        //将点击确定后的图片保存在另一个redis数据库中
        Jedis resource = jedisPool.getResource();
        String image = address.getImage();
        if (image != null) {
            resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, image);
            resource.close();
        }
    }

    @Override
    public void delete(Integer id) {
        Integer count = addressDao.findCountById(id);
        if(count>0){
             throw new AddressDeleteFailException();
        }else {
            addressDao.delete(id);
        }
    }
}
